
package com.kugou.game.sdk.core;

import com.kugou.framework.base.AppException;
import com.kugou.game.sdk.api.common.BaseSDKConfig;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.entity.AccountSecurityInfo;
import com.kugou.game.sdk.entity.CouponListResponse;
import com.kugou.game.sdk.entity.PayRecord;
import com.kugou.game.sdk.entity.ResponseMessage;
import com.kugou.game.sdk.interfaces.OnBindPhoneListener;
import com.kugou.game.sdk.interfaces.OnCheckAnswerListener;
import com.kugou.game.sdk.interfaces.OnCheckPhoneIsBindedListener;
import com.kugou.game.sdk.interfaces.OnCheckUserBindedPhoneListener;
import com.kugou.game.sdk.interfaces.OnEditMessageListener;
import com.kugou.game.sdk.interfaces.OnGetPasswdMethodListener;
import com.kugou.game.sdk.interfaces.OnLoadFAQDetailListener;
import com.kugou.game.sdk.interfaces.OnLoadFAQListListener;
import com.kugou.game.sdk.interfaces.OnLoadMessageInfoListener;
import com.kugou.game.sdk.interfaces.OnLoadMessageListListener;
import com.kugou.game.sdk.interfaces.OnLoadPayRecordListener;
import com.kugou.game.sdk.interfaces.OnLoginListener;
import com.kugou.game.sdk.interfaces.OnModifyPasswordListener;
import com.kugou.game.sdk.interfaces.OnQueryYoubiNumListener;
import com.kugou.game.sdk.interfaces.OnRegisterListener;
import com.kugou.game.sdk.interfaces.OnRequestGamecenterRedPointListener;
import com.kugou.game.sdk.interfaces.OnRequestListener;
import com.kugou.game.sdk.interfaces.OnRequestUserIdCardListener;
import com.kugou.game.sdk.interfaces.OnRequestValidateCodeListener;
import com.kugou.game.sdk.interfaces.OnRequestValidateCodeV3Listener;
import com.kugou.game.sdk.interfaces.OnResetPasswordListener;
import com.kugou.game.sdk.interfaces.OnTempUserCreateListener;
import com.kugou.game.sdk.interfaces.onAccountSecurityInfoListener;
import com.kugou.game.sdk.protocol.AccountSecurityInfoTask;
import com.kugou.game.sdk.protocol.AccountSecurityInfoTask.AccountSecurityInfoResponse;
import com.kugou.game.sdk.protocol.BindPhoneTask;
import com.kugou.game.sdk.protocol.BindPhoneTask.BindPhoneResponse;
import com.kugou.game.sdk.protocol.BindTempAccountTask;
import com.kugou.game.sdk.protocol.BindTempAccountTask.BindTempAccountResponse;
import com.kugou.game.sdk.protocol.ChargeHistoryTask;
import com.kugou.game.sdk.protocol.ChargeHistoryTask.CheckCostRecordsResponse;
import com.kugou.game.sdk.protocol.CheckAnswerTask;
import com.kugou.game.sdk.protocol.CheckAnswerTask.CheckAnswerResponse;
import com.kugou.game.sdk.protocol.CheckGiftBagTask;
import com.kugou.game.sdk.protocol.CheckGiftBagTask.CheckGiftBagResponse;
import com.kugou.game.sdk.protocol.CheckPhoneIsBindedTask;
import com.kugou.game.sdk.protocol.CheckPhoneIsBindedTask.checkPhonenumberResponse;
import com.kugou.game.sdk.protocol.CheckUserBindedPhoneTask;
import com.kugou.game.sdk.protocol.CheckUserBindedPhoneTask.CheckIsBindPhoneResponse;
import com.kugou.game.sdk.protocol.DistributeAccountTask;
import com.kugou.game.sdk.protocol.DistributeAccountTask.AccountResponse;
import com.kugou.game.sdk.protocol.EditMessageTask;
import com.kugou.game.sdk.protocol.EditMessageTask.EditMessageHttpResponse;
import com.kugou.game.sdk.protocol.FAQDetailTask;
import com.kugou.game.sdk.protocol.FAQDetailTask.FAQDetailHttpResponse;
import com.kugou.game.sdk.protocol.FAQListTask;
import com.kugou.game.sdk.protocol.FAQListTask.FAQListHttpResponse;
import com.kugou.game.sdk.protocol.GetPasswordByProblemTask;
import com.kugou.game.sdk.protocol.GetPasswordByProblemTask.GetPasswordByProblemResponse;
import com.kugou.game.sdk.protocol.LoginTask;
import com.kugou.game.sdk.protocol.LoginTask.LoginResponse;
import com.kugou.game.sdk.protocol.MessageInfoTask;
import com.kugou.game.sdk.protocol.MessageInfoTask.MessageInfoHttpResponse;
import com.kugou.game.sdk.protocol.MessageListTask;
import com.kugou.game.sdk.protocol.MessageListTask.MessageListHttpResponse;
import com.kugou.game.sdk.protocol.ModifyPasswordTask;
import com.kugou.game.sdk.protocol.ModifyPasswordTask.ModifyPasswordResponse;
import com.kugou.game.sdk.protocol.ModifyUserHeadTask;
import com.kugou.game.sdk.protocol.ModifyUserHeadTask.ModifyUserHeadResponse;
import com.kugou.game.sdk.protocol.PayPsdCodeTask;
import com.kugou.game.sdk.protocol.PayPsdCodeTask.PayPsdCodeResponse;
import com.kugou.game.sdk.protocol.QueryKubiNumTask;
import com.kugou.game.sdk.protocol.QueryKubiNumTask.QueryKubiNumHttpResponse;
import com.kugou.game.sdk.protocol.RegisterByAccoutTask;
import com.kugou.game.sdk.protocol.RegisterByAccoutTask.RegisterByAccountResponse;
import com.kugou.game.sdk.protocol.RegisterByAutoTask;
import com.kugou.game.sdk.protocol.RegisterByAutoTask.RegisterByAutoResponse;
import com.kugou.game.sdk.protocol.RegisterByPhoneTask;
import com.kugou.game.sdk.protocol.RegisterByPhoneTask.RegisterByPhoneResponse;
import com.kugou.game.sdk.protocol.RequestEmailValidateCodeTask;
import com.kugou.game.sdk.protocol.RequestGamecenterRedpointTask;
import com.kugou.game.sdk.protocol.RequestGamecenterRedpointTask.GameRedpointResponse;
import com.kugou.game.sdk.protocol.RequestGetPasswdMethodTask;
import com.kugou.game.sdk.protocol.RequestGetPasswdMethodTask.RequestGetpasswdMethodResponse;
import com.kugou.game.sdk.protocol.RequestHistoryCouponTask;
import com.kugou.game.sdk.protocol.RequestUsableCouponTask;
import com.kugou.game.sdk.protocol.RequestUserCenterBannerTask;
import com.kugou.game.sdk.protocol.RequestUserCenterBannerTask.UserCenterBannerResponse;
import com.kugou.game.sdk.protocol.RequestValidateCodeTaskV3;
import com.kugou.game.sdk.protocol.RequestValidateCodeTaskV3.RequestVerifiyCodeResponseV3;
import com.kugou.game.sdk.protocol.ResetPasswordTaskV3;
import com.kugou.game.sdk.protocol.ResetPasswordTaskV3.ResetPasswordResponseV3;
import com.kugou.game.sdk.protocol.ResetPayPsdTask;
import com.kugou.game.sdk.protocol.ResetPayPsdTask.ResetPayPsdResponse;
import com.kugou.game.sdk.protocol.SecurityEmailCodeTask;
import com.kugou.game.sdk.protocol.SecurityEmailCodeTask.SecurityEmailCodeResponse;
import com.kugou.game.sdk.protocol.SetLoginPsdTask;
import com.kugou.game.sdk.protocol.SetLoginPsdTask.SetLoginPsdResponse;
import com.kugou.game.sdk.protocol.SetPayPsdTask;
import com.kugou.game.sdk.protocol.SetPayPsdTask.SetPayPsdResponse;
import com.kugou.game.sdk.protocol.SetSecurityEmailTask;
import com.kugou.game.sdk.protocol.SetSecurityEmailTask.SetSecurityEmailResponse;
import com.kugou.game.sdk.protocol.SetSecurityQuestionTask;
import com.kugou.game.sdk.protocol.SetSecurityQuestionTask.SetSecurityQuestionResponse;
import com.kugou.game.sdk.protocol.UpdateBindPhoneTask;
import com.kugou.game.sdk.protocol.UpdateBindPhoneTask.UpdateBindPhoneResponse;
import com.kugou.game.sdk.protocol.UpdateIDCardTask;
import com.kugou.game.sdk.protocol.UpdateIDCardTask.UpdateIDCardResponse;
import com.kugou.game.sdk.protocol.UpdateNickNameTask;
import com.kugou.game.sdk.protocol.UpdateNickNameTask.UpdateNickNameResponse;
import com.kugou.game.sdk.protocol.UpdatePayPsdTask;
import com.kugou.game.sdk.protocol.UpdatePayPsdTask.UpdatePayPsdResponse;
import com.kugou.game.sdk.protocol.UpdateSecurityEmailTask;
import com.kugou.game.sdk.protocol.UpdateSecurityEmailTask.UpdateSecurityEmailResponse;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.FileUtil;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述:用户中心，单例模式
 * 
 * @author liux
 * @since 2013-12-2 下午8:13:51
 */
public class UserManager {

    private static final String REQUEST_FAIL = "网络请求失败";

    private static UserManager mInstance;

    private User currentUser;// 当前登录用户信息

    private UserManager() {
    }

    /**
     * 获取实例
     * 
     * @return
     */
    public static UserManager getInstance() {
        if (mInstance == null) {
            synchronized (UserManager.class) {
                if (mInstance == null) {
                    mInstance = new UserManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 将用户信息转为字节数
     * 
     * @param user 用户信息
     * @return byte[]
     */
    private static byte[] getBytes(User user) {
        try {
            JSONObject data = new JSONObject();
            // SDK5.4.0起，服务端增加kopenid作为用户唯一标识,SDK增加openId与之对应。SDK5.4.0之前，是用userName作为唯一标识。
            // 在本地信息的读和写时，做不同版本之间字段的映射，保证版本兼容。旧username<-->新openid;旧nickName<-->新userName
            data.put("userName", user.getOpenId() == null ? "" : user.getOpenId());
            data.put("nickName", user.getAccountName() == null ? "" : user.getAccountName());
            data.put("password", user.getPassword() == null ? "" : user.getPassword());
            data.put("userType", user.getUserType());

            data.put("signature", user.getSignature() == null ? "" : user.getSignature());
            data.put("sex", user.getSex() == null ? "" : user.getSex());
            data.put("birthday", user.getBirthday() == null ? "" : user.getBirthday());
            data.put("age", user.getAge() == null ? "" : user.getAge());
            data.put("province", user.getProvince() == null ? "" : user.getProvince());
            data.put("city", user.getCity() == null ? "" : user.getCity());
            data.put("headIconUrl", user.getHeadIconUrl() == null ? "" : user.getHeadIconUrl());
            data.put("trueName", user.getTrueName() == null ? "" : user.getTrueName());
            data.put("securityEmail",
                    user.getSecurityEmail() == null ? "" : user.getSecurityEmail());

            data.put("kugouTokenAppId", user.getKugouTokenAppId());
            data.put("kugouToken", user.getKugouToken() == null ? "" : user.getKugouToken());
            String str = data.toString();
            if (!TextUtils.isEmpty(str)) {
                return str.getBytes();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取取本应用下保存的最近登录的用户信息的文件路径
     * 
     * @return
     */
    private static String getLatestUserDataFilePathOnSp() {
        String path = SDKControler
                .getContext()
                .getSharedPreferences(FolderManager.LAST_USER_DATA_PATH_SETTING,
                        Context.MODE_PRIVATE)
                .getString(FolderManager.LAST_USER_DATA_FILE_PATH, null);
        return path;
    }

    /**
     * 获取SD卡上保存的最新登录的用户数据文件路径
     * 
     * @return 用户数据文件路径
     */
    private static String getLatestUserDataFilePathOnSDcard() {
        if (!FileUtil.isSDCardAvailable()) {
            return null;
        }

        byte[] data = null;
        int gameType = SDKControler.getGameType();
        if (gameType == BaseSDKConfig.GAME_TYPE_ONLINE) {
            if (FileUtil.isExist(FolderManager.CONFIG_FILE)) {
                data = FileUtil.getFileData(FolderManager.CONFIG_FILE);
            }
        } else {
            if (FileUtil.isExist(FolderManager.CONFIG_FILE_FOR_SINGLE)) {
                data = FileUtil.getFileData(FolderManager.CONFIG_FILE_FOR_SINGLE);
            }
        }

        if (data != null && data.length > 0) {
            // 先解密
            AppUtil.unEncrypt(data);
            String json = new String(data);
            if (!TextUtils.isEmpty(json)) {
                try {
                    JSONObject jsonObj = new JSONObject(json);
                    String userDataFilePath = jsonObj
                            .getString(FolderManager.LAST_USER_DATA_FILE_PATH);
                    return userDataFilePath;
                } catch (Exception e) {
                }
            }
        }

        return null;
    }

    /**
     * 保存最新登录的用户数据文件路径
     * 
     * @param userDataFilePath 用户数据文件路径
     */
    private static void saveLatestUserDataFilePath(String userDataFilePath) {
        // 保存在本应用SharedPreferrence
        SDKControler
                .getContext()
                .getSharedPreferences(FolderManager.LAST_USER_DATA_PATH_SETTING,
                        Context.MODE_PRIVATE).edit()
                .putString(FolderManager.LAST_USER_DATA_FILE_PATH, userDataFilePath).commit();

        // 保存到SD卡
        if (TextUtils.isEmpty(userDataFilePath)) {
            return;
        }
        if (!FileUtil.isSDCardAvailable()) {
            return;
        }

        if (!FileUtil.isExist(FolderManager.CONFIG_FILE)) {
            FileUtil.createFile(FolderManager.CONFIG_FILE, FileUtil.MODE_COVER);
        }
        if (!FileUtil.isExist(FolderManager.CONFIG_FILE_FOR_SINGLE)) {
            FileUtil.createFile(FolderManager.CONFIG_FILE_FOR_SINGLE, FileUtil.MODE_COVER);
        }

        JSONObject jsonObj = new JSONObject();
        try {
            jsonObj.put(FolderManager.LAST_USER_DATA_FILE_PATH, userDataFilePath);
            byte[] data = jsonObj.toString().getBytes();
            // 先加密
            AppUtil.encrypt(data);

            // 根据游戏类型保存在不同的目录
            int gameType = SDKControler.getGameType();
            if (gameType == BaseSDKConfig.GAME_TYPE_ONLINE) {
                FileUtil.rewriteData(FolderManager.CONFIG_FILE, data);
            } else {
                FileUtil.rewriteData(FolderManager.CONFIG_FILE_FOR_SINGLE, data);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 生成用户数据文件保存路径
     * 
     * @param userData 用户信息
     * @return
     */
    private static String createUserDataFilePath(User userData) {
        if (userData == null) {
            return "";
        }
        return FolderManager.USER_DATA_FOLDER + userData.getOpenId()
                + FolderManager.USER_DATA_FILE_EXT;
    }

    /**
     * 生成用户数据文件保存路径
     * 
     * @param openid
     * @return
     */
    private static String createUserDataFilePath(String openid) {
        if (TextUtils.isEmpty(openid)) {
            return "";
        }
        return FolderManager.USER_DATA_FOLDER + openid + FolderManager.USER_DATA_FILE_EXT;
    }

    /**
     * 根据用户唯一标识查找本地用户信息
     * 
     * @param openid
     * @return
     */
    private User getLocalUserData(String openid) {
        String path = createUserDataFilePath(openid);
        User user = loadUserFile(path);
        return user;
    }

    /**
     * 保存正式（注册）用户信息到本地
     * 
     * @param user
     */
    public boolean saveUserData(User user) {
        try {
            if (user == null) {
                return false;
            }
            if (!FileUtil.isSDCardAvailable()) {
                return false;
            }
            String filePath = createUserDataFilePath(user);
            if (!FileUtil.isExist(filePath)) {
                FileUtil.createFile(filePath, FileUtil.MODE_COVER);
            }
            byte[] data = getBytes(user);

            // 先加密
            AppUtil.encrypt(data);
            FileUtil.rewriteData(filePath, data);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除用户（账号）信息
     * 
     * @param user
     * @return boolean
     */
    public boolean deleteUserData(User user) {
        try {
            if (user == null) {
                return false;
            }
            if (!FileUtil.isSDCardAvailable()) {
                return false;
            }
            String filePath = createUserDataFilePath(user);
            if (FileUtil.isExist(filePath)) {
                FileUtil.deleteFile(filePath);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 保存最新登录用户数据到本地
     * 
     * @param user
     * @return
     */
    public boolean saveLatestUserData(User user) {
        try {
            String path = createUserDataFilePath(user);
            saveLatestUserDataFilePath(path);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取SP最新登录用户数据
     * 
     * @return user
     */
    public User getLastestUserDataOnSP() {
        if (!FileUtil.isSDCardAvailable()) {
            return null;
        }
        User user = null;
        try {
            // 读取本应用目录下保存的最新登录的账号信息
            String latestUserDataFilePathOnSp = getLatestUserDataFilePathOnSp();
            user = loadUserFile(latestUserDataFilePathOnSp);
            if (user != null) {
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取SD卡里最新用户信息
     * 
     * @return
     */
    public User getLastestUserDataOnSDcard() {
        if (!FileUtil.isSDCardAvailable()) {
            return null;
        }

        User user = null;
        try {
            // 获取本地SD卡单机和网游可共用的正式账号中最新登录的账号信息
            ArrayList<User> registeredUsers = getAllRegistedUsers();
            if (registeredUsers != null && registeredUsers.size() > 0) {
                return registeredUsers.get(0);
            }

            // 读取SD卡保存的单机或网游所对应的最新登录的账号信息
            String latestUserDataFilePathOnSDcard = getLatestUserDataFilePathOnSDcard();
            user = loadUserFile(latestUserDataFilePathOnSDcard);
            if (user != null) {
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析用户信息文件生成用户User对象
     * 
     * @param filePath
     * @return
     */
    private User loadUserFile(String filePath) {
        if (FileUtil.isExist(filePath)) {
            byte[] data = FileUtil.getFileData(filePath);
            if (data != null && data.length > 0) {
                // 先解密
                AppUtil.unEncrypt(data);
                String json = new String(data);
                if (!TextUtils.isEmpty(json)) {
                    try {
                        JSONObject jsonObj = new JSONObject(json);
                        String openid = jsonObj.getString("userName");
                        String username = jsonObj.getString("nickName");
                        String password = jsonObj.getString("password");
                        int userType = jsonObj.getInt("userType");
                        String kugouToken = "";
                        long kugouTokenAppId = 0;
                        if (!jsonObj.isNull("kugouToken") && !jsonObj.isNull("kugouTokenAppId")) {
                            kugouToken = jsonObj.getString("kugouToken");
                            kugouTokenAppId = jsonObj.getLong("kugouTokenAppId");
                        }
                        User userData = new User(openid, username, password, userType);
                        userData.setKugouToken(kugouToken);
                        userData.setKugouTokenAppId(kugouTokenAppId);
                        return userData;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取所有正式（注册）账号信息
     * 
     * @return
     */
    public ArrayList<User> getAllRegistedUsers() {
        try {
            if (!FileUtil.isSDCardAvailable()) {
                return null;
            }
            if (FileUtil.isExist(FolderManager.USER_DATA_FOLDER)) {
                int gameType = SDKControler.getGameType();

                List<File> files = FileUtil.getFileSort(FolderManager.USER_DATA_FOLDER);
                if (files == null || files.size() == 0) {
                    return null;
                }
                ArrayList<User> datas = new ArrayList<User>();
                for (File file : files) {
                    byte[] data = FileUtil.getFileData(file.getAbsolutePath());
                    if (data != null && data.length > 0) {
                        // 先解密
                        AppUtil.unEncrypt(data);
                        String json = new String(data);
                        if (!TextUtils.isEmpty(json)) {
                            try {
                                JSONObject jsonObj = new JSONObject(json);
                                String openid = jsonObj.getString("userName");
                                String username = jsonObj.getString("nickName");
                                String password = jsonObj.getString("password");
                                int userType = jsonObj.getInt("userType");
                                String kugouToken = "";
                                long kugouTokenAppId = 0;
                                if (!jsonObj.isNull("kugouToken")
                                        && !jsonObj.isNull("kugouTokenAppId")) {
                                    kugouToken = jsonObj.getString("kugouToken");
                                    kugouTokenAppId = jsonObj.getLong("kugouTokenAppId");
                                }
                                if (userType == User.REGISTED_USER) {
                                    User userData = new User(openid, username, password, userType);
                                    userData.setKugouToken(kugouToken);
                                    userData.setKugouTokenAppId(kugouTokenAppId);

                                    // 单机和网游的临时账号通过绑定成为的正式账号不能共用
                                    if (gameType == BaseSDKConfig.GAME_TYPE_ONLINE) {
                                        if (openid.length() != 32) {// 单机的临时账号是本地生成，长度32位
                                            datas.add(userData);
                                        }
                                    } else {
                                        if (!openid.contains("_")) {// 网游的临时账号是服务端生成，判断规则是有带下划线"_"
                                            datas.add(userData);
                                        }
                                    }
                                }
                            } catch (Exception e) {
                            }
                        }
                    }
                }
                return datas;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前登录用户信息(library层使用)
     * 
     * @return
     */
    public User getCurrentUserInternal() {
        return currentUser;
    }

    /**
     * 获取当前登录用户信息
     * 
     * @return
     */
    public User getCurrentUser() {
        if (currentUser != null) {
            return currentUser.copySimpleUser();
        } else {
            return null;
        }
    }

    /**
     * 保存当前登录用户信息的:获取/更新/修改/
     */
    public void setCurrentUser(User user) {
        // 保存当前登录用户信息
        currentUser = user;
        // 保存最新登录信息
        saveLatestUserData(user);
        // 保存用户信息
        saveUserData(user);
    }

    /**
     * 保存当前用户信息在内存中
     * 
     * @param user
     */
    public void setCurrentUserInMemory(User user) {
        currentUser = user;
    }

    /**
     * 是否正式用户登录状态
     * 
     * @return true登录 false 未登录
     */
    public boolean isLogin() {
        return currentUser != null && currentUser.getUserType() == User.REGISTED_USER;
    }

    /**
     * 判断当前账号是否绑定了手机
     * 
     * @return true 已绑定 false 没有绑定手机
     */
    public boolean isBindPhone() {
        if (currentUser != null) {
            if (!TextUtils.isEmpty(currentUser.getBindPhoneNum())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 分配临时账号
     * 
     * @param listener
     */
    public void createTempUser(OnTempUserCreateListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnTempUserCreateListener can't be null");
        }

        DistributeAccountTask task = new DistributeAccountTask();
        AccountResponse response = task.request();
        if (response != null) {
            if (response.isUseful()) {
                User user = new User();
                user.setOpenId(response.getOpenid());
                user.setAccountName(response.getUserName());
                user.setNickName(response.getNickName());
                user.setToken(response.getToken());
                user.setUnixTime(response.getUnixtime());
                user.setPassword("");
                user.setUserType(User.TEMP_USER);
                user.setKubiNum(response.getKubiNum());
                // 保存用户信息
                setCurrentUser(user);
                listener.onSuccess(user);
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed("分配临时账号失败");
        }
    }

    /**
     * 登录
     * 
     * @param username
     * @param password
     * @param verifytype 验证方式：默认0：密码验证1：第三token验证
     * @param appid 当前应用appid
     * @param tAppId 对应kugouToken的appId
     * @param listener
     */
    public void login(String username, String password, long appid, int verifytype, long tAppId,
            OnLoginListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnLoginListener can't be null");
        }

        LoginTask task = new LoginTask();
        LoginResponse response = task.request(username, password, verifytype, tAppId);

        if (response != null) {
            if (response.isUseful()) {
                User user = new User();
                user.setOpenId(response.getOpenid());
                user.setAccountName(response.getUserName());
                user.setNickName(response.getNickName());
                if (verifytype == 0) {
                    user.setPassword(password);
                } else {
                    // 530版本前kugoutoken与tAppid为对应关系
                    // user.setKugouTokenAppId(tAppId);
                }
                // 530版本后返回的kugoutoken改为与当前应用appid为对应关系
                user.setKugouTokenAppId(appid);
                user.setKugouToken(response.getKugouToken());

                user.setToken(response.getToken());
                user.setKugouid(response.getKugouUserId());
                user.setUnixTime(response.getUnixtime());
                // 账号类型--0：正式帐号，1：临时帐号
                int accountType = response.getAccountType();
                if (accountType == 0) {
                    user.setUserType(User.REGISTED_USER);
                } else {
                    user.setUserType(User.TEMP_USER);
                }
                // 绑定手机号
                String bindPhone = response.getBindedphone();
                if (!TextUtils.isEmpty(bindPhone)) {
                    user.setBindPhoneNum(bindPhone);
                } else {
                    user.setBindPhoneNum("");
                }
                // 游币余额
                user.setKubiNum(response.getKubiNum());
                user.setUnreadmails(response.getUnReadMails());
                // 用户头像地址
                user.setHeadIconUrl(response.getHeadIconUrl());
                // 用户真实姓名
                user.setTrueName(response.getTrueName());
                // 安全邮箱
                user.setSecurityEmail(response.getSecurityEmail());
                // 登录邮箱
                user.setLoginEmail(response.getLoginEmail());
                // 酷狗的正式账号是否设置了登录密码（第三方账号登录没有密码）
                if (accountType == 0) {
                    user.setSetKugouPsd(response.getSetKugouPsd() == 1);
                }
                // 保存用户信息
                setCurrentUser(user);
                listener.onSuccess(user);
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    public void registerByAccount(String userName, String tempName, String password,
            OnRegisterListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRegisterListener can't be null");
        }

        try {
            RegisterByAccoutTask task = new RegisterByAccoutTask();
            RegisterByAccountResponse response = task.request(userName, tempName, password);
            if (response != null) {
                if (response.isUseful()) {
                    User user = new User();
                    user.setOpenId(response.getOpenId());
                    user.setAccountName(response.getUserName());
                    user.setNickName(response.getNickName());
                    user.setPassword(password);
                    user.setKugouTokenAppId(SDKControler.getAppId());
                    user.setKugouToken(response.getKugouToken());
                    user.setToken(response.getToken());
                    user.setKugouid(response.getKugouUserId());
                    user.setUnixTime(response.getUnixtime());
                    user.setUserType(User.REGISTED_USER);
                    // 游币余额
                    user.setKubiNum(response.getKubiNum());
                    user.setUnreadmails(response.getUnreadmails());
                    // 保存用户信息
                    setCurrentUser(user);
                    listener.onSuccess(user);
                } else if ("19".equals(response.getCode())
                        && response.getRecommendUsernames() != null) {
                    if (response.getRecommendUsernames().size() != 0) {
                        ArrayList<String> names = response.getRecommendUsernames();
                        listener.onRecommendRegisterName(names);
                    } else {
                        listener.onFailed(response.getPrompt(), response.getCode());
                    }
                } else {
                    listener.onFailed(response.getPrompt(), response.getCode());
                }
            } else {
                listener.onFailed(REQUEST_FAIL, "");
            }
        } catch (AppException e) {
            listener.onFailed(REQUEST_FAIL, e.getType() + "");
        }
    }

    public void registerByPhone(String mobile, String tempName, String checkcode,
            OnRegisterListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRegisterListener can't be null");
        }

        try {
            RegisterByPhoneTask task = new RegisterByPhoneTask();
            RegisterByPhoneResponse response = task.request(mobile, tempName, checkcode);
            if (response != null) {
                if (response.isUseful()) {
                    User user = new User();
                    user.setOpenId(response.getOpenId());
                    user.setAccountName(response.getUserName());
                    user.setNickName(response.getNickName());
                    if (!TextUtils.isEmpty(response.getPassword())) {
                        user.setPassword(AppUtil.desDecrypt(response.getPassword()));
                    }
                    user.setKugouTokenAppId(SDKControler.getAppId());
                    user.setKugouToken(response.getKugouToken());
                    user.setToken(response.getToken());
                    user.setKugouid(response.getKugouUserId());
                    user.setUnixTime(response.getUnixtime());
                    user.setUserType(User.REGISTED_USER);
                    user.setBindPhoneNum(mobile);
                    // 游币余额
                    user.setKubiNum(response.getKubiNum());
                    user.setUnreadmails(response.getUnreadmails());
                    // 保存用户信息
                    setCurrentUser(user);
                    listener.onSuccess(user);
                } else {
                    listener.onFailed(response.getPrompt(), response.getCode());
                }
            } else {
                listener.onFailed(REQUEST_FAIL, "");
            }
        } catch (AppException e) {
            listener.onFailed(REQUEST_FAIL, e.getType() + "");
        }
    }

    public void registerByAuto(String tempName, OnRegisterListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRegisterListener can't be null");
        }

        try {
            RegisterByAutoTask task = new RegisterByAutoTask();
            RegisterByAutoResponse response = task.request(tempName);
            if (response != null) {
                if (response.isUseful()) {
                    if (currentUser == null) {
                        currentUser = new User();
                    }
                    currentUser.setOpenId(response.getOpenId());
                    currentUser.setAccountName(response.getUserName());
                    currentUser.setNickName(response.getNickName());
                    if (!TextUtils.isEmpty(response.getPassword())) {
                        currentUser.setPassword(AppUtil.desDecrypt(response.getPassword()));
                    }
                    currentUser.setKugouTokenAppId(SDKControler.getAppId());
                    currentUser.setKugouToken(response.getKugouToken());
                    currentUser.setToken(response.getToken());
                    currentUser.setKugouid(response.getKugouUserId());
                    currentUser.setUnixTime(response.getUnixtime());
                    currentUser.setUserType(User.REGISTED_USER);
                    // 游币余额
                    currentUser.setKubiNum(response.getKubiNum());
                    currentUser.setUnreadmails(response.getUnreadmails());
                    // 保存用户信息
                    setCurrentUser(currentUser);
                    listener.onSuccess(currentUser);
                } else {
                    listener.onFailed(response.getPrompt(), response.getCode());
                }
            } else {
                listener.onFailed(REQUEST_FAIL, "");
            }
        } catch (AppException e) {
            listener.onFailed(REQUEST_FAIL, e.getType() + "");
        }
    }

    public void bindTempAccout(String userName, String tempName, long appid, String kgtoken,
            OnRegisterListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRegisterListener can't be null");
        }

        try {
            BindTempAccountTask task = new BindTempAccountTask();
            BindTempAccountResponse response = task.request(userName, tempName, appid, kgtoken);
            if (response != null) {
                if (response.isUseful()) {
                    User user = new User();
                    user.setOpenId(response.getOpenId());
                    user.setAccountName(response.getUserName());
                    user.setNickName(response.getNickName());
                    user.setKugouTokenAppId(SDKControler.getAppId());
                    user.setKugouToken(response.getKugouToken());
                    user.setToken(response.getToken());
                    user.setKugouid(response.getKugouUserId());
                    user.setUnixTime(response.getUnixtime());
                    user.setUserType(User.REGISTED_USER);
                    // 游币余额
                    user.setKubiNum(response.getKubiNum());
                    user.setUnreadmails(response.getUnreadmails());
                    // 保存用户信息
                    setCurrentUser(user);
                    listener.onSuccess(user);
                } else {
                    listener.onFailed(response.getPrompt(), response.getCode());
                }
            } else {
                listener.onFailed(REQUEST_FAIL, "");
            }
        } catch (AppException e) {
            listener.onFailed(REQUEST_FAIL, e.getType() + "");
        }
    }

    /**
     * 修改密码
     * 
     * @param userName 用户名
     * @param oldPwd 旧密码
     * @param newPwd 新密码
     * @param listener
     */
    public void modifyPassword(String userName, String oldPwd, String newPwd,
            OnModifyPasswordListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnModifyPasswordListener can't be null");
        }

        ModifyPasswordTask task = new ModifyPasswordTask();
        ModifyPasswordResponse response = task.request(userName, oldPwd, newPwd);
        if (response != null) {
            if (response.isUseful()) {
                if (currentUser != null) {
                    // 保存新密码
                    currentUser.setPassword(newPwd);
                    currentUser.setKugouTokenAppId(SDKControler.getAppId());
                    currentUser.setKugouToken(response.getKugouToken());
                    // 保存用户信息
                    setCurrentUser(currentUser);
                }
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 验证手机号是否有绑定(核实验证码)
     * 
     * @param userName
     * @param number
     * @param smsCheckCode
     * @param listener
     */
    public void checkPhoneIsBinded(String userName, String number, String smsCheckCode,
            OnCheckPhoneIsBindedListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnCheckPhoneIsBindedListener can't be null");
        }

        CheckPhoneIsBindedTask task = new CheckPhoneIsBindedTask();
        checkPhonenumberResponse response = task.request(userName, number, smsCheckCode);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess(response.getUnixtime(), response.getToken());
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 绑定手机
     * 
     * @param userName 用户名
     * @param mobilePhone 手机号码
     * @param smsCheckCode 验证码
     * @param listener
     */
    public void bindPhone(String userName, String mobilePhone, String smsCheckCode,
            String password, OnBindPhoneListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnBindPhoneListener can't be null");
        }
        BindPhoneTask task = new BindPhoneTask();
        BindPhoneResponse response = task.request(userName, mobilePhone, smsCheckCode, password);
        if (response != null) {
            if (response.isUseful()) {
                if (currentUser != null) {
                    currentUser.setBindPhoneNum(mobilePhone);
                    currentUser.setSecurityScore(response.getSecurityScore());
                    setCurrentUser(currentUser);
                }
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 更新绑定手机号码
     * 
     * @param userName
     * @param mobilePhone
     * @param smsCheckCode
     * @param unixtime
     * @param token
     * @param listener
     */
    public void updateBindPhone(String userName, String mobilePhone, String smsCheckCode,
            String unixtime, String token, OnBindPhoneListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnBindPhoneListener can't be null");
        }
        UpdateBindPhoneTask task = new UpdateBindPhoneTask();
        UpdateBindPhoneResponse response = task.request(userName, mobilePhone, smsCheckCode,
                unixtime, token);
        if (response != null) {
            if (response.isUseful()) {
                if (currentUser != null) {
                    currentUser.setBindPhoneNum(mobilePhone);
                    // 手机号注册的账号，修改绑定手机号后，酷狗平台会同时修改nickname字段，所以也需要更新nickname字段
                    currentUser.setAccountName(response.getNickname());
                    setCurrentUser(currentUser);
                }
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 检测用户是否已经绑定手机号
     * 
     * @param userName 用户名
     * @param kgToken
     * @param listener
     */
    public void checkUserBindedPhone(String userName, String kgToken,
            OnCheckUserBindedPhoneListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnCheckUserBindedPhoneListener can't be null");
        }

        CheckUserBindedPhoneTask task = new CheckUserBindedPhoneTask();
        CheckIsBindPhoneResponse response = task.request(userName, kgToken);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess(null);
            } else if ("23".equals(response.getCode())
                    && !TextUtils.isEmpty(response.getBindedPhone())) {
                listener.onSuccess(response.getBindedPhone());
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 查询充值消费记录
     * 
     * @param merchantId
     * @param appId
     * @param userName
     * @param appKey
     * @param listener
     */
    public void getPayRecordList(String userName, OnLoadPayRecordListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnLoadPayRecordListener can't be null");
        }

        ChargeHistoryTask task = new ChargeHistoryTask();
        CheckCostRecordsResponse response = task.request(userName);
        if (response != null) {
            if (response.isUseful()) {
                ArrayList<PayRecord> data = response.getArrayListData();
                listener.onSuccess(data);
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 获取消息列表
     * 
     * @param Username
     * @param Page 从1开始
     * @param Pagesize 请求消息条数
     * @param listener
     */
    public void getMessageList(String Username, int Page, int Pagesize, String lastMessageUnixTime,
            OnLoadMessageListListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnLoadMessageListListener can't be null");
        }
        MessageListTask task = new MessageListTask();
        MessageListHttpResponse response = task.request(Username, Page, Pagesize,
                lastMessageUnixTime);
        if (response != null && response.isOk()) {
            if (response.isUseful()) {
                listener.onSuccess(response.getMessageList());
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 获取消息详情
     * 
     * @param userName
     * @param Messageid
     * @param listener
     */
    public void getMessageInfo(String userName, int Messageid, OnLoadMessageInfoListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnLoadMessageInfoListener can't be null");
        }
        MessageInfoTask task = new MessageInfoTask();
        MessageInfoHttpResponse response = task.request(userName, Messageid);
        if (response != null && response.isOk()) {
            if (response.isUseful()) {
                listener.onSuccess(response.getMessageInfo());
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 编辑消息
     * 
     * @param appId 本应用的appId
     * @param username
     * @param password
     * @param Action readmessage=读,delmessage=删除
     * @param messageIds 消息ID字符串,多个请用,号分隔
     * @param source 0=使用登陆密码，1=使用酷狗token
     * @param tAppId 对应kugouToken的appId
     * @param pageIndex 该条消息对应的页码
     * @param pageSize 请求的消息条数
     * @param listener
     */
    public void editMessageItem(String username, String Action, String messageIds, int pageIndex,
            int pageSize, OnEditMessageListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnEditMessageListener can't be null");
        }

        EditMessageTask task = new EditMessageTask();
        EditMessageHttpResponse response = task.request(username, Action, messageIds, pageIndex,
                pageSize);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 请求游戏中心的红点数据
     * 
     * @param listener
     */
    public void requestGamecenterRedpointTip(String kugouid, String imei, int nettype, String mid,
            String uuid, OnRequestGamecenterRedPointListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestGamecenterRedPointListener can't be null");
        }

        RequestGamecenterRedpointTask task = new RequestGamecenterRedpointTask();
        GameRedpointResponse response = task.request(kugouid, imei, nettype, mid, uuid);
        if (response != null && response.isOk()) {
            listener.onSuccess(response.getResponse());
        }
    }

    /**
     * 本地生成单机临时账号信息
     * 
     * @param context
     * @return
     */
    public User createSingleUserDataByLocal(Context context) {
        String openid = AppUtil.getUIDForSingle(context);
        User userData = new User(openid, openid, "", User.TEMP_USER);
        userData.setKugouToken("");
        userData.setKugouTokenAppId(0);
        // 保存用户信息
        setCurrentUser(userData);

        return userData;
    }

    /**
     * 生成游客登录账号
     * 
     * @param context
     * @return
     */
    public User getSingleUserDataForGuest(Context context) {
        User user = getLastestUserDataOnSP();
        if (user != null) {
            setCurrentUser(user);
            return user;
        }
        user = getLastestUserDataOnSDcard();
        if (user != null) {
            setCurrentUser(user);
            return user;
        }
        return createSingleUserDataByLocal(context);
    }

    /**
     * 获取最新登录用户数据
     * 
     * @return user
     */
    public User getLastestUserDataOnSPAndSDcard() {
        if (currentUser != null) {
            return currentUser;
        }
        if (!FileUtil.isSDCardAvailable()) {
            return null;
        }

        User user = null;
        try {
            // 读取本应用目录下保存的最新登录的账号信息
            String latestUserDataFilePathOnSp = getLatestUserDataFilePathOnSp();
            user = loadUserFile(latestUserDataFilePathOnSp);
            if (user != null) {
                return user;
            }

            // 获取本地SD卡单机和网游可共用的正式账号中最新登录的账号信息
            ArrayList<User> registeredUsers = getAllRegistedUsers();
            if (registeredUsers != null && registeredUsers.size() > 0) {
                return registeredUsers.get(0);
            }

            // 读取SD卡保存的单机或网游所对应的最新登录的账号信息
            String latestUserDataFilePathOnSDcard = getLatestUserDataFilePathOnSDcard();
            user = loadUserFile(latestUserDataFilePathOnSDcard);
            if (user != null) {
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前用户名
     * 
     * @return
     */
    public String getCurrentUserName() {
        if (currentUser != null && currentUser.isRegistered()) {
            return currentUser.getAccountName();
        } else {
            return "您还没登录";
        }
    }

    /**
     * 请求验证码（服务端V3版）
     * 
     * @param smstype 1：手机注册；2：绑定手机；3：找回密码
     * @param mobile
     * @param listener
     */
    public void requestValidateCodeV3(String username, int smstype, String mobile,
            OnRequestValidateCodeV3Listener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestValidateCodeListener can't be null");
        }

        try {
            RequestValidateCodeTaskV3 task = new RequestValidateCodeTaskV3();
            RequestVerifiyCodeResponseV3 response = task.request(username, smstype, mobile);
            if (response != null) {
                if (response.isUseful()) {
                    listener.onSuccess(response.getUnixTime(), response.getToken());
                } else {
                    listener.onFailed(response.getPrompt(), response.getCode());
                }
            } else {
                listener.onFailed(REQUEST_FAIL, "");
            }
        } catch (AppException e) {
            listener.onFailed(REQUEST_FAIL, e.getType() + "");
        }
    }

    /**
     * 重置密码（服务端V3版）
     * 
     * @param mobile
     * @param newPsd
     * @param smscheckcode
     * @param unixTime
     * @param token
     * @param listener
     */
    public void resetPasswordV3(String mobile, String username, String newPsd, String smscheckcode,
            String unixTime, String token, OnResetPasswordListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnResetPasswordListener can't be null");
        }

        ResetPasswordTaskV3 task = new ResetPasswordTaskV3();
        ResetPasswordResponseV3 response = task.request(mobile, newPsd, smscheckcode, unixTime,
                token);
        if (response != null) {
            if (response.isUseful()) {
                String openid = response.getOpenid();
                User user = null;
                if (!TextUtils.isEmpty(openid)) {
                    user = getLocalUserData(openid);
                    if (user != null) {// 如果本地已有信息记录，则更新密码，否则新增写入本地
                        if (currentUser != null && openid.equals(currentUser.getOpenId())) {
                            currentUser.setPassword(newPsd);
                            currentUser.setKugouTokenAppId(SDKControler.getAppId());
                            currentUser.setKugouToken(response.getKugouToken());
                            setCurrentUser(currentUser);
                        } else {
                            user.setPassword(newPsd);
                            saveUserData(user);
                        }
                    } else {
                        user = new User(openid, username, newPsd, User.REGISTED_USER);
                        saveUserData(user);
                    }
                }
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 请求发送邮箱验证码
     * 
     * @param username
     * @param email
     * @param listener
     */
    public void requestEmailValidateCode(String username, String email,
            OnRequestValidateCodeListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestValidateCodeListener can't be null");
        }

        try {
            RequestEmailValidateCodeTask task = new RequestEmailValidateCodeTask();
            ResponseMessage response = task.request(username, email);
            if (response != null) {
                if (response.isUseful() && response.isOk()) {
                    listener.onSuccess();
                } else {
                    listener.onFailed(response.getPrompt(), response.getCode());
                }
            } else {
                listener.onFailed(REQUEST_FAIL, "");
            }
        } catch (AppException e) {
            listener.onFailed(REQUEST_FAIL, e.getType() + "");
        }
    }

    /**
     * 获取取回密码方式
     * 
     * @param userName
     * @param listener
     */
    public void getPasswdMethod(String userName, OnGetPasswdMethodListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener not be null");
        }

        try {
            RequestGetPasswdMethodTask task = new RequestGetPasswdMethodTask();
            RequestGetpasswdMethodResponse response = task.request(userName);

            if (response != null) {
                if (response.isUseful()) {
                    listener.onSuccess(response.getEmail(), response.getMobile(),
                            response.getQuestionId());
                } else {
                    listener.onFailed(response.getPrompt());
                }

            }
        } catch (Exception e) {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 验证密保问题
     * 
     * @param userName
     * @param answer
     * @param questionId
     * @param listener
     */
    public void checkAnswer(String userName, String answer, int questionId,
            OnCheckAnswerListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener not be null");
        }

        try {
            CheckAnswerTask task = new CheckAnswerTask();
            CheckAnswerResponse response = task.request(userName, answer, questionId);

            if (response != null) {
                if (response.isUseful()) {
                    listener.onSuccess(response.getToken(), response.getUnixtime());
                } else {
                    listener.onFailed(response.getPrompt());
                }
            } else {
                listener.onFailed(REQUEST_FAIL);
            }
        } catch (Exception e) {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 密保问题取回密码
     * 
     * @param username
     * @param token
     * @param unixtime
     * @param password
     * @param listener
     */
    public void getPasswdByProblem(String username, String token, String unixtime, String password,
            OnRequestListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener not be null");
        }

        try {
            GetPasswordByProblemTask task = new GetPasswordByProblemTask();
            GetPasswordByProblemResponse response = task.request(username, password, unixtime,
                    token);

            if (response != null) {
                if (response.isUseful()) {
                    String openid = response.getOpenid();
                    User user = null;
                    if (!TextUtils.isEmpty(openid)) {
                        user = getLocalUserData(openid);
                        if (user != null) {// 如果本地已有信息记录，则更新密码，否则新增写入本地
                            if (currentUser != null && openid.equals(currentUser.getOpenId())) {
                                currentUser.setPassword(password);
                                currentUser.setKugouTokenAppId(SDKControler.getAppId());
                                currentUser.setKugouToken(response.getKugouToken());
                                setCurrentUser(currentUser);
                            } else {
                                user.setPassword(password);
                                saveUserData(user);
                            }
                        } else {
                            user = new User(openid, username, password, User.REGISTED_USER);
                            saveUserData(user);
                        }
                    }
                    listener.onSuccess();
                } else {
                    listener.onFailed(response.getPrompt());
                }
            } else {
                listener.onFailed(REQUEST_FAIL);
            }
        } catch (Exception e) {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 请求账号安全信息
     * 
     * @param listener
     */
    public void requestAccountSecurityInfo(onAccountSecurityInfoListener listener) {
        if (listener == null) {
            throw new RuntimeException("onAccountSecurityInfoListener not be null");
        }

        AccountSecurityInfoTask task = new AccountSecurityInfoTask();
        AccountSecurityInfoResponse response = task.request(getCurrentUserName(),
                getCurrentUserInternal().getKugouToken());
        if (response != null) {
            if (response.isOk()) {
                AccountSecurityInfo info = response.getInfo();
                currentUser.setSecurityScore(info.getSecurityScore());
                currentUser.setLoginEmail(info.getLoginEmail());
                currentUser.setSecurityEmail(info.getSecurityEmail());
                currentUser.setSecurityQuestionId(info.getSecurityQuestionId());
                currentUser.setSetIdentity(info.isSetIdentity());
                currentUser.setPayPsd(info.getPayPsd());
                listener.onSuccess(info);
            } else {
                listener.onFaile(response.getPrompt());
            }
        } else {
            listener.onFaile(REQUEST_FAIL);
        }
    }

    /**
     * 发送验证码到安全邮箱
     * 
     * @param username
     * @param kgToken
     * @param email
     * @param type 操作类型1：新增安全邮箱，2：旧安全邮箱验证码（更新操作时往旧邮箱发送）
     * @param listener
     */
    public void sendSecurityEmailCode(String username, String kgToken, String email, int type,
            OnRequestListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener not be null");
        }

        SecurityEmailCodeTask task = new SecurityEmailCodeTask();
        SecurityEmailCodeResponse response = task.request(username, kgToken, email, type);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 设置安全邮箱
     * 
     * @param username
     * @param email
     * @param checkcode
     * @param password
     * @param listener
     */
    public void setSecurityEmail(String username, String email, String checkcode, String password,
            onAccountSecurityInfoListener listener) {
        if (listener == null) {
            throw new RuntimeException("onAccountSecurityInfoListener not be null");
        }

        SetSecurityEmailTask task = new SetSecurityEmailTask();
        SetSecurityEmailResponse response = task.request(username, email, checkcode, password);
        if (response != null) {
            if (response.isOk()) {
                AccountSecurityInfo info = response.getInfo();
                currentUser.setSecurityEmail(email);
                currentUser.setLoginEmail(info.getLoginEmail());
                currentUser.setSecurityScore(info.getSecurityScore());
                listener.onSuccess(info);
            } else {
                listener.onFaile(response.getPrompt());
            }
        } else {
            listener.onFaile(REQUEST_FAIL);
        }
    }

    /**
     * 更新（修改）安全邮箱
     * 
     * @param username
     * @param kgToken
     * @param email
     * @param checkcode
     * @param listener
     */
    public void updateSecurityEmail(String username, String kgToken, String email,
            String checkcode, OnRequestListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener not be null");
        }

        UpdateSecurityEmailTask task = new UpdateSecurityEmailTask();
        UpdateSecurityEmailResponse response = task.request(username, kgToken, email, checkcode);
        if (response != null) {
            if (response.isUseful()) {
                currentUser.setSecurityEmail(email);
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 设置密保问题
     * 
     * @param username
     * @param questionid
     * @param answer
     * @param password
     * @param listener
     */
    public void setSecurityQuestion(String username, int questionid, String answer,
            String password, onAccountSecurityInfoListener listener) {
        if (listener == null) {
            throw new RuntimeException("onAccountSecurityInfoListener not be null");
        }

        SetSecurityQuestionTask task = new SetSecurityQuestionTask();
        SetSecurityQuestionResponse response = task.request(username, questionid, answer, password);
        if (response != null) {
            if (response.isOk()) {
                AccountSecurityInfo info = response.getInfo();
                currentUser.setSecurityQuestionId(info.getSecurityQuestionId());
                currentUser.setSecurityScore(info.getSecurityScore());
                listener.onSuccess(response.getInfo());
            } else {
                listener.onFaile(response.getPrompt());
            }
        } else {
            listener.onFaile(REQUEST_FAIL);
        }
    }

    /**
     * 设置支付密码
     * 
     * @param username
     * @param password
     * @param paypassword
     * @param listener
     */
    public void setPayPsd(String username, String password, String paypassword,
            onAccountSecurityInfoListener listener) {
        if (listener == null) {
            throw new RuntimeException("onAccountSecurityInfoListener not be null");
        }

        SetPayPsdTask task = new SetPayPsdTask();
        SetPayPsdResponse response = task.request(username, password, paypassword);
        if (response != null) {
            if (response.isUseful()) {
                AccountSecurityInfo info = response.getInfo();
                currentUser.setPayPsd(info.getPayPsd());
                currentUser.setSecurityScore(info.getSecurityScore());
                listener.onSuccess(response.getInfo());
            } else {
                listener.onFaile(response.getPrompt());
            }
        } else {
            listener.onFaile(REQUEST_FAIL);
        }
    }

    /**
     * 修改/更新支付密码
     * 
     * @param username
     * @param kgToken
     * @param oldPayPassword
     * @param newPayPassword
     * @param listener
     */
    public void updatePayPsd(String username, String kgToken, String oldPayPassword,
            String newPayPassword, OnRequestListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener not be null");
        }

        UpdatePayPsdTask task = new UpdatePayPsdTask();
        UpdatePayPsdResponse response = task.request(username, kgToken, oldPayPassword,
                newPayPassword);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 重置支付密码发送验证码
     * 
     * @param username
     * @param mobile
     * @param listener
     */
    public void sendPayPsdCode(String username, String mobile, OnRequestListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener not be null");
        }

        PayPsdCodeTask task = new PayPsdCodeTask();
        PayPsdCodeResponse response = task.request(username, mobile);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 重置支付密码
     * 
     * @param username
     * @param kgToken
     * @param smscheckcode
     * @param newPayPassword
     * @param listener
     */
    public void resetPayPsd(String username, String kgToken, String smscheckcode,
            String newPayPassword, OnRequestListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener not be null");
        }

        ResetPayPsdTask task = new ResetPayPsdTask();
        ResetPayPsdResponse response = task
                .request(username, kgToken, smscheckcode, newPayPassword);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 请求礼包状态
     */
    public void requestGiftBagState(OnRequestListener listener) {
        CheckGiftBagTask task = new CheckGiftBagTask();
        CheckGiftBagResponse response = task.request(getCurrentUserName());
        if (response != null && response.isOk()) {
            currentUser.setCanGetGift(response.getGiftBagAllowedCount() > 0);
            currentUser.setHasGift(response.getGiftBagTotalCount() > 0);
            if (response.getGiftBagTotalCount() > 0) {
                if (listener != null) {
                    listener.onSuccess();
                }
            }
        }
    }

    /**
     * 更新用户身份证信息
     */
    public void updateUserIdCard(String username, String password, String idCard, String truename,
            OnRequestUserIdCardListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnUpdateIdCardListener can't be null");
        }
        UpdateIDCardTask task = new UpdateIDCardTask();
        UpdateIDCardResponse response = task.request(username, password, idCard, truename);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 更新用户头像
     */
    public void updateUserHead(String username, File file, OnRequestListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener can't be null");
        }
        ModifyUserHeadTask task = new ModifyUserHeadTask();
        ModifyUserHeadResponse response = task.request(username, file);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 获取FAQ列表
     */
    public void requestFAQList(OnLoadFAQListListener onLoadFAQListListener) {
        if (onLoadFAQListListener == null) {
            throw new RuntimeException("OnRequestListener can't be null");
        }
        FAQListTask task = new FAQListTask();
        FAQListHttpResponse response = task.request();
        if (response != null) {
            if (response.isUseful()) {
                onLoadFAQListListener.onSuccess(response.getFAQList());
            } else {
                onLoadFAQListListener.onFailed(response.getPrompt());
            }
        } else {
            onLoadFAQListListener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 获取FAQ详情
     */
    public void requestFAQDetail(int titleId, OnLoadFAQDetailListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener can't be null");
        }
        FAQDetailTask task = new FAQDetailTask();
        FAQDetailHttpResponse response = task.request(titleId);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess(response.getFAQDetail());
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 请求后端游币余额，更新当前用户游币余额
     */
    public void updateYoubiNum() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                queryYoubiNum(new OnQueryYoubiNumListener() {

                    @Override
                    public void onSuccess(int youbiNum) {
                        UserManager.getInstance().getCurrentUserInternal().setKubiNum(youbiNum);

                        Intent intent = new Intent(SDKActions.ACTION_KUBI_NUM_CHANGE);
                        SDKControler.getContext().sendBroadcast(intent);
                    }

                    @Override
                    public void onFailed(String errorMsg) {

                    }
                });

            }
        }).start();
    }

    /**
     * 查询游币余额
     * 
     * @param username
     * @param kgToken
     * @param listener
     */
    public void queryYoubiNum(OnQueryYoubiNumListener listener) {

        QueryKubiNumTask task = new QueryKubiNumTask();
        QueryKubiNumHttpResponse response = task.request(UserManager.getInstance()
                .getCurrentUserName(), UserManager.getInstance().getCurrentUserInternal()
                .getKugouToken());
        if (response != null) {
            if (response.isUseful()) {
                if (listener != null) {
                    listener.onSuccess(response.getResult_kbleft());
                }
            } else {
                if (listener != null) {
                    listener.onFailed(response.getPrompt());
                }
            }
        } else {
            if (listener != null) {
                listener.onFailed(REQUEST_FAIL);
            }
        }

    }

    /**
     * 第三方登录设置登录密码
     */
    public void setLoginPsd(String username, String newPwd, OnRequestListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener can't be null");
        }
        SetLoginPsdTask task = new SetLoginPsdTask();
        SetLoginPsdResponse response = task.request(username, newPwd);
        if (response != null) {
            if (response.isUseful()) {
                currentUser.setPassword(newPwd);
                currentUser.setSetKugouPsd(true);
                currentUser.setUnreadmails(response.getUnreadmails());
                setCurrentUser(currentUser);
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 请求用户中心Banner信息
     */
    public void requestUserCenterBanner(OnRequestListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener can't be null");
        }
        RequestUserCenterBannerTask task = new RequestUserCenterBannerTask();
        UserCenterBannerResponse response = task.request();
        if (response != null) {
            if (response.isUseful() && response.isOk()) {
                currentUser.setBannerInfo(response.getUserCenterBannerInfo());
                listener.onSuccess();
            } else {
                listener.onFailed(REQUEST_FAIL);
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

    /**
     * 请求可用代金券列表
     */
    public CouponListResponse requestUsableCouponList(int pageIndex, int pageSize, String userName) {
        RequestUsableCouponTask task = new RequestUsableCouponTask();
        CouponListResponse response = task.request(pageIndex, pageSize, userName);
        return response;
    }

    /**
     * 请求历史代金券列表
     */
    public CouponListResponse requestHistoryCouponList(int pageIndex, int pageSize, String userName) {
        RequestHistoryCouponTask task = new RequestHistoryCouponTask();
        CouponListResponse response = task.request(pageIndex, pageSize, userName);
        return response;
    }

    /**
     * 更新用户昵称
     */
    public void updateNickName(String newNickName, String userName, OnRequestListener listener) {
        if (listener == null) {
            throw new RuntimeException("OnRequestListener can't be null");
        }
        UpdateNickNameTask task = new UpdateNickNameTask();
        UpdateNickNameResponse response = task.request(newNickName, userName);
        if (response != null) {
            if (response.isUseful()) {
                listener.onSuccess();
            } else {
                listener.onFailed(response.getPrompt());
            }
        } else {
            listener.onFailed(REQUEST_FAIL);
        }
    }

}
